import Head from "next/head";
import { useCallback, useEffect, useRef, useState } from "react";
import axios from "axios";
import { Button } from '@mantine/core';
import Layout from "@/common/layout";
import Item from "@/common/components/item";
import {SystemAxios,ClientAxios} from '@/common/useAxios'

function List({list=[],hasMove}){
    const [currList,setCurrList] = useState(list)
    const currPage  = useRef(1);
    const hasMoveRef = useRef(hasMove)
    const ajaxState = useRef(false)
    const getList = useCallback((page)=>{
        ClientAxios.post('/home/article_list',{
            pageSize:10,
            type:'list',
            page:page
        }).then(({data:res})=>{
            if(res.code == 1){
                currPage.current = res.data.currpage
                setCurrList(list=>{
                    return list.concat(res.data.list)
                })
            }
            hasMoveRef.current = res.data.hasMove;
            ajaxState.current = false;
        })
    },[])
    useEffect(()=>{
        const scrollfn = ()=>{
            if(!hasMoveRef.current || ajaxState.current){return}
            var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
            var scrllHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
            if((scrllHeight - scrollTop - window.innerHeight) <200){
                //加载下一页
                ajaxState.current = true;
                getList(currPage.current+1)
            }
        }
        //处理滚动事件
        window.addEventListener('scroll', scrollfn)
        return ()=>{
            window.removeEventListener('scroll', scrollfn)
        }
    },[])
    return (
        <>
            <Layout title={'列表页'}>
                {
                    currList.map((v,i)=>{
                        return (
                            <Item data={v} key={i} />
                        )
                    })
                }
            </Layout>
        </>
    )
}
export async function getServerSideProps(context){
    const {data:res} = await SystemAxios({
        method: 'get',
        url: '/home/article_list',
        params: { pageSize:10,type:'list',page:1},
    })
    if(res.code == 1){
        return {
            props:{
                list:res.data.list,
                hasMove:res.data.hasMove
            }
        }
    }else{
        return {
            props:{
                list:[]
            }
        }
    }
}
export default List